<template>
  <div
    :class="[
      'ra-tree-search-wrapper',
      'transition-all duration-300 ease-in-out',
      isVisible ? 'w-1/5 min-w-[280px] p-r-4' : 'w-0 p-r-0 overflow-hidden',
    ]"
  >
    <div class="m-1 p-2 main_area">
      <!-- 顶部控制区域 -->
      <el-row :gutter="10">
        <el-col :span="12">
          <el-input
            v-model="filterText"
            placeholder="输入关键字过滤"
            clearable
          />
        </el-col>
        <el-col :span="12" class="flex justify-end items-center">
          <el-tooltip
            effect="dark"
            :content="expand ? '全部收起' : '全部展开'"
            placement="top"
          >
            <el-button @click="toggleRowExpansion">
              <el-icon>
                <component :is="expand ? ArrowUp : ArrowDown" />
              </el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="重置" placement="top">
            <el-button @click="handleReset" class="ml-2">
              <el-icon><RefreshRight /></el-icon>
            </el-button>
          </el-tooltip>
        </el-col>
      </el-row>

      <!-- 树形组件 -->
      <el-tree
        ref="treeRef"
        class="filter-tree"
        :data="processedTreeData"
        :props="{ children: 'children', label: 'label' }"
        :filter-node-method="filterNode"
        :default-expand-all="expand"
        node-key="value"
        :current-node-key="selectedValue"
        highlight-current
        @node-click="handleNodeClick"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import {
  ElTree,
  ElInput,
  ElRow,
  ElCol,
  ElTooltip,
  ElIcon,
  ElButton,
} from 'element-plus';
import { ArrowUp, ArrowDown, RefreshRight } from '@element-plus/icons-vue';

// 1. Props 定义
const props = defineProps({
  // 接收树形或扁平列表数据
  treeList: {
    type: Array,
    default: () => [],
  },
  // 用于生成搜索条件的字段名
  fieldName: {
    type: String,
    default: 'status',
  },
  // 控制侧边栏的可见性
  isVisible: {
    type: Boolean,
    default: true,
  },
  // **新增：v-model 绑定**
  modelValue: {
    type: [String, Number],
    default: '',
  },
});

// 2. 事件定义
const emit = defineEmits(['query', 'update:modelValue']);

// 3. 响应式状态
const filterText = ref('');
const expand = ref(true); // 默认展开
const treeRef = ref(null);
// 修正：使用 prop 或默认值初始化
const selectedValue = ref(props.modelValue || '');

// 监听外部 modelValue 变化，同步内部状态
watch(
  () => props.modelValue,
  (newVal) => {
    selectedValue.value = newVal || '';
  },
);

// 4. 核心：自动处理传入的数据
const processedTreeData = computed(() => {
  if (!props.treeList || props.treeList.length === 0) {
    return [];
  }

  const firstItem = props.treeList[0];
  const isTree =
    firstItem && typeof firstItem === 'object' && 'children' in firstItem;

  let data;

  if (isTree) {
    data = props.treeList;
  } else {
    data = props.treeList.map((item) => ({
      label: item.label,
      value: item.value,
    }));
  }

  // 统一在最前面添加“全部”选项
  return [{ label: '全部', value: '' }, ...data];
});

// 5. 监听和方法
// 监听筛选文本变化
watch(filterText, (val) => {
  treeRef.value?.filter(val);
});

// 节点筛选方法
const filterNode = (value, data) => {
  if (!value) return true;
  return String(data.label).includes(value);
};

// 节点点击事件
const handleNodeClick = (data) => {
  const newValue = data.value;
  if (selectedValue.value === newValue) {
    // 避免重复点击
    return;
  }

  // 1. 更新内部状态
  selectedValue.value = newValue;

  // 2. 发射 update:modelValue 事件，实现 v-model 绑定
  emit('update:modelValue', newValue);

  // 3. 发射 query 事件，通知父组件进行查询
  const filterValue = newValue === '' ? undefined : newValue;
  emit('query', {
    fieldName: props.fieldName,
    value: filterValue,
  });
};

// 切换所有节点的展开/收起状态
const toggleRowExpansion = () => {
  expand.value = !expand.value;
  const nodes = treeRef.value?.store.nodesMap;
  if (nodes) {
    for (const key in nodes) {
      if (nodes[key].childNodes && nodes[key].childNodes.length > 0) {
        nodes[key].expanded = expand.value;
      }
    }
  }
};

// 重置功能
const handleReset = () => {
  filterText.value = '';
  selectedValue.value = '';

  // 1. 发射 update:modelValue 事件
  emit('update:modelValue', '');

  // 2. 发射 query 事件
  emit('query', {
    fieldName: props.fieldName,
    value: undefined,
  });

  treeRef.value?.setCurrentKey(null);
};

// 将重置方法暴露给父组件，以便外部调用
defineExpose({
  reset: handleReset,
  selectedValue,
});

// 初始设置选中项
watch(
  [() => processedTreeData.value, selectedValue],
  ([newTreeData, newSelectedValue]) => {
    if (newTreeData.length > 0 && newSelectedValue) {
      treeRef.value?.setCurrentKey(newSelectedValue);
    }
  },
  { immediate: true },
);
</script>

<style scoped>
.ra-tree-search-wrapper {
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.main_area {
  border: 1px solid #eee;
  border-radius: 5px;
  height: calc(100vh - 100px) !important;
}

.filter-tree {
  /* 自动填充剩余空间并允许滚动 */
  overflow-y: auto;
  flex-grow: 1;
  /* 设置一个最小高度，防止在 flex 容器中被过度压缩 */
  min-height: 200px;
  margin-top: 10px;
}

/* 优化 Element Plus 按钮和图标的对齐 */
.el-button.is-circle {
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 高亮节点的样式 */
:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: #ecf5ff;
  color: #409eff;
  font-weight: bold;
}
</style>
